"""
登陆校验
date 2021-01-04
"""

from  django.views import View
from  django.http import HttpResponse,JsonResponse
from  django.shortcuts import render
from  django.db import connection
import time
import hashlib
from .lib import redisPool


# 防SQL 注入,过滤前端传来的字符串
class Check_sql():

    @staticmethod
    def Check_sql(pram):
        dirty_stuff = ["\"", "\\", "/", "*", "'", "=", "-", "#", ";", "<", ">", "+", "%", "$", "(", ")", "%", "@", "!"]
        for stuff in dirty_stuff:
            pram = pram.replace(stuff, "")
        return pram

# 登陆校验，写入redis
class LoginCheck(View):
    def __init__(self):
        self.ID ="eomsId"

    def get(self, request):
        return HttpResponse('请使用Post方法调用该接口!')

    def post(self, request):
        print(request.POST)

        __account    =  Check_sql.Check_sql(request.POST.get('account'))
        __password   =  request.POST.get('password')
        # __checkCode  =  request.POST.get('checkCode')  # 前端自己生成和验证
        __ID         =  request.POST.get('ID')

        # 参数完整性校验
        if __account==None or __password==None or __ID==None:
            return JsonResponse({'code': 400, 'err': '缺少参数！'})



            # exit()
        # 密码加密
        secret = hashlib.md5()
        secret.update(__password.encode(encoding='utf-8'))
        password_secret = secret.hexdigest()
        # print('user:'+__account)

        if self.ID != __ID:
            return JsonResponse({'code': 300, 'err': '您的身份不明确，请检查ID号，或者联系管理员 13585586574'})

        try:
            with connection.cursor() as cursor:
                sql = "select password from ums_user where nick_name= '%s'"%(__account)
                cursor.execute(sql)
                raw = cursor.fetchone()
                # print(sql)

            if raw is None:
                return JsonResponse({'code': 400, 'err': 'userniek or password is err！'})
            elif raw[0] == password_secret:

            # if raw is  None or raw[0] == password_secret :
                # 生成token
                token = hashlib.md5()
                token.update( (str(time.time()) + __account).encode('utf-8'))
                tokenSecret = token.hexdigest()

                # session存入redis
                key = tokenSecret
                value = tokenSecret+'^'+__account
                #value=123
                self.saveRedis(key,value)

                # 返回报文
                response ={
                    "code":200,
                    "msg":"successful",
                    "token":tokenSecret,
                }
                return JsonResponse(response)
            else:
                return JsonResponse({'code':400,'err':'userniek or password is err！'})
        except Exception as e :
            return JsonResponse({"err":str(e)})


    def  saveRedis(self,key,value):
        pool =redisPool.pool
        pool.set(key,value,ex=3600)

# 获取用户列表
class Getuserinfomation(View):

    def get(self,request):
        return HttpResponse("请使用Post方法调用该接口")

    def post(self,request):

        # 连接数据库
        with connection.cursor() as cursor:
            sql = "select nick_name,real_name from ums_user" # where nick_name= '%s'" % (__account)
            cursor.execute(sql)
            raw = cursor.fetchall()
            userlist ={}
            n =0
            for x in raw:
                #print(x[1])
                userlist[n+1]=x
                n+=1
            #print(  userlist )
        return JsonResponse(userlist)

# 获取整个用户信息（弃用）
class Auth(View):
    def __init__(self):
        self._key = "a123"

    def get(self, request):
        return HttpResponse('请使用Post调用该接口!')

    def post(self, request):

        account = request.POST.get('account')
        token = request.POST.get('token')
        if account == None or token == None or token != self._key:
        #if account == None or token == None or token != str(123):
            return JsonResponse({'message': '参数错误！请检查后调用！'})
        try:
            with connection.cursor() as cursor:
                cursor.execute("select * from y_account where account= '%s'" % (account))
                raw = cursor.fetchall()
                # print(raw)
        except Exception as e:
            return HttpResponse(str(e))

        auth_data = {
            ''
            'ID': raw[0][0],
            'account': raw[0][1],
            'account_name': raw[0][2],
            'role_id': raw[0][3],
            'sex': raw[0][4],
            'age': raw[0][5],
            'wechat_num': raw[0][6],
            'mobile_num': raw[0][7],
            'status': raw[0][8],
            'CREATED_BY': raw[0][9],
            'CREATED_TIME': raw[0][10],
            'UPDATED_BY': raw[0][11],
            'UPDATED_TIME': raw[0][12],
            'del_status': raw[0][13],
        }

        # auth_data = json.dumps(auth_data)
        dates = time.strftime('%Y-%m-%d %H:%M:%S')
        return JsonResponse(auth_data)


# 添加用户
class Adduser(View):

    def get(self, request):
        return HttpResponse('请使用Post调用该接口!')
    def post(self,request):


        return HttpResponse("It's adduser")



    #return None

# 添加角色
class Addrole(View):

    def get(self, request):
        return HttpResponse('请使用Post调用该接口!')
    def post(self,request):


        return HttpResponse("It's addrole")



    #return None